<script setup lang="ts">
	//供应商发布营销
	import { onMounted, ref } from "vue";
	import {
		validatePhoneNumber
	} from '@/utlis/common.js'
	import {
		getCurrentInstance
	} from 'vue'
	import {
		onShow,
		onHide,
		onLoad
	} from '@dcloudio/uni-app'
	import form from "../../../uni_modules/uview-plus/libs/config/props/form";
	import {
		userStore
	} from '@/pinia';
	import {
		useRouter
	} from 'uni-mini-router'
	let router = useRouter()
	const userStoreInfo = userStore();
	const {
		proxy,
	} = getCurrentInstance()
	onLoad((options) => {
		console.log(options, "打印options");
		//此处的data，需要用来请求营销类型，从组件内，和详情内都带过来一份
		itemId.value = options.id
		console.log(itemId.value, "打印itemId。value")
		if (itemId.value) {
			//获取详情回显
			getDetail()
		}
		pageObj.value = JSON.parse(options.data)
	})
	onMounted(() => {

	})
	const getDetail = () => {
		//回显
		proxy.$req('GET', proxy.$api.getServiceDetail, {
			id: itemId.value
		}).then((res) => {
			console.log(res, "打印res");
			fileList.value.fileList0 = JSON.parse(res.result.images)
			fileList.value.fileList5 = JSON.parse(res.result.thumbnail)
			gysForm.value.title = res.result.title
			gysForm.value.companyName = res.result.companyName
			gysForm.value.merchantAdvantages = res.result.merchantAdvantages
			fileList.value.fileList1 = JSON.parse(res.result.merchantAdvantagesImage)
			gysForm.value.serviceType = res.result.serviceType
			fileList.value.fileList2 = JSON.parse(res.result.serviceTypeImage)
			gysForm.value.lawFirmProfile = res.result.lawFirmProfile
			fileList.value.fileList3 = JSON.parse(res.result.lawFirmProfileImage)
			gysForm.value.serviceProgram = res.result.serviceProgram
			fileList.value.fileList4 = JSON.parse(res.result.serviceProgramImage)
			gysForm.value.address = res.result.address
			gysForm.value.contactUser = res.result.contactUser
			gysForm.value.contactPhone = res.result.contactPhone
			gysForm.value.latitude = res.result.latitude
			gysForm.value.longitude = res.result.longitude
		})
	}
	let itemId = ref('')
	let pageObj = ref({})
	let form1 = ref(null)
	let marketType = ref([])
	let gysForm = ref({
		title: '',
		latitude: '',
		longitude: '',
		merchantAdvantages: '',
		serviceProgram: '',
		lawFirmProfile: '',
		serviceType: '',
		contactPhone: '',
		address: '',
		contactUser: '',
		companyName: ''
	})
	let gysRules = ref({
		type: {},
		title: {
			required: true,
			message: '请输入正确内容',
			trigger: ['change']
		},
		merchantAdvantages: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		serviceType: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		lawFirmProfile: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		serviceProgram: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		contactUser: {
			required: true,
			message: '请输入正确内容',
			trigger: ['change']
		},
		contactPhone: [{
			required: true,
			message: '手机号码必填',
		},
		{
			validator: (rule, value, callback) => {
				console.log(value);
				return validatePhoneNumber(value);
			},
			message: '手机号码不正确',
			trigger: ['change'],
		}],
	})
	const afterRead = (e, type) => {
		// console.log(fileList.value[`fileList${type}`], 'fileList[type]');
		// [`fileList${type}`]
		console.log(e);
		const item = e.file;
		// fileList.value[`fileList${type}`].push({
		// 	...item,
		// 	//提示上传中
		// 	status: 'uploading',
		// 	message: '上传中'
		// });
		uni.showLoading({
			title: '上传中',
		})
		for (let a = 0; a <= item.length; a++) {
			uni.uploadFile({
				url: proxy.$uploadUrl + proxy.$api.uploadFile,
				filePath: item[a].url,
				name: 'file',
				formData: {
					file: item[a].url,
				},
				success: (uploadFileRes) => {
					console.log(JSON.parse(uploadFileRes.data));
					if (!JSON.parse(uploadFileRes.data).success) {
						uni.showToast({
							title: JSON.parse(uploadFileRes.data).message,
							icon: 'none'
						})
						// setTimeout(() => {
						// 	fileList.value[`fileList${type}`].splice(-1)
						// }, 700)
						return
					}
					let result = JSON.parse(uploadFileRes.data).result
					// console.log(result, 'result');
					uni.hideLoading()
					fileList.value[`fileList${type}`].push(
						// item[a]
						Object.assign({}, {
							// status: 'success',
							// message: '上传成功',
							url: result,
							thumb: result
						})
					);
					console.log(fileList.value[`fileList${type}`]);
				},
				complete() { }
			});
		}

	}
	const deletePic = (e, type) => {
		console.log(e);
		fileList.value[`fileList${type}`].splice(e.index, 1)
	}
	let fileList = ref({
		fileList0: [],
		fileList1: [],
		fileList2: [],
		fileList3: [],
		fileList4: [],
		fileList5: [],
	})
	const submitForm = () => {
		//校验图片
		// Object.keys(gysForm.value).forEach(key => {
		// 	console.log(key);
		// })
		//校验表单内图片和描述至少上传一项
		//设置表单label和上传图片的响应数组对应
		let labelObj = {
			fileList1: 'merchantAdvantages',
			fileList2: 'serviceType',
			fileList3: 'lawFirmProfile',
			fileList4: 'serviceProgram',
		}
		let toastObj = {
			merchantAdvantages: '商家优势图片和文字至少存在一项',
			serviceType: '服务类型图片和文字至少存在一项',
			lawFirmProfile: '律所介绍图片和文字至少存在一项',
			serviceProgram: '服务项目图片和文字至少存在一项',
		}
		let err = ''
		//循环上传图片数组，判断图片和文字是否有一项为空（缩略图没有label，给个固定值）
		Object.keys(fileList.value).forEach((key) => {
			// console.log(key);
			if (fileList.value[key].length < 1 && !gysForm.value[labelObj[key]]) {
				console.log('错误的', key, labelObj[key]);
				err = toastObj[labelObj[key]]
				return
			}
		})
		if (err) {
			uni.showToast({
				title: err,
				icon: 'none'
			})
			return
		}
		//校验表单
		form1.value.validate().then(res => {
			let url;
			let methods;
			if (itemId.value) {
				url = proxy.$api.editService
				methods = 'put'
			} else {
				url = proxy.$api.addService
				methods = 'post'
			}
			if (fileList.value.fileList0.length == 0) {
				uni.$u.toast("请选择顶部图片")
				return
			}
			if (fileList.value.fileList5.length == 0) {
				uni.$u.toast("请选择顶缩略图")
				return
			}
			proxy.$req(methods, url, {
				id: itemId.value ? itemId.value : '',
				supplierId: userStoreInfo.userInfo.supplier.id,
				images: JSON.stringify(fileList.value.fileList0),
				title: gysForm.value.title,
				merchantAdvantages: gysForm.value.merchantAdvantages,
				merchantAdvantagesImage: JSON.stringify(fileList.value.fileList1),
				serviceType: gysForm.value.serviceType,
				serviceTypeImage: JSON.stringify(fileList.value.fileList2),
				lawFirmProfile: gysForm.value.lawFirmProfile,
				lawFirmProfileImage: JSON.stringify(fileList.value.fileList3),
				serviceProgram: gysForm.value.serviceProgram,
				serviceProgramImage: JSON.stringify(fileList.value.fileList4),
				thumbnail: JSON.stringify(fileList.value.fileList5),
				address: gysForm.value.address,
				latitude: gysForm.value.latitude,
				longitude: gysForm.value.longitude,
				companyName: gysForm.value.companyName,
				contactUser: gysForm.value.contactUser,
				contactPhone: gysForm.value.contactPhone,
			}).then((res) => {
				console.log(res, 'ressubmit');
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
				if (res.success) {
					uni.$emit('refreshServe', {})
					setTimeout(() => {
						uni.navigateBack()
					}, 600)
				}
			})
		}).catch(errors => {
			console.log(errors);
			uni.showToast({
				title: '请检查表单',
				icon: 'none'
			})
		})
	}
	const getMapChoseAddress = () => {
		uni.chooseLocation({
			success: function (res) {
				console.log('位置名称：' + res.name);
				console.log('详细地址：' + res.address);
				console.log('纬度：' + res.latitude);
				console.log('经度：' + res.longitude);
				gysForm.value.address = res.address
				gysForm.value.companyName = res.name
				gysForm.value.latitude = String(res.latitude)
				gysForm.value.longitude = String(res.longitude)
			}
		});
	}
	const goAuth = () => {
		router.push({
			name: 'authRole',
			params: {}
		})
	}
</script>
<template>
	<view style="padding:16rpx 32rpx;background-color: #F2E6E7;" class="r-flex-between-center"
		v-if="userStoreInfo.userFlag==2?userStoreInfo.userInfo.supplier.isReal!=1:userStoreInfo.userFlag==1?userStoreInfo.userInfo.shoppingStore.isReal!=1:false">
		<text style="color: #FF6C6C;font-size: 28rpx;font-weight: 600;">企业未认证，认证后可发布营销信息</text>
		<view style="background-color: #FF6B6B;color: #fff;font-size: 22rpx;padding: 10rpx 20rpx;border-radius: 60rpx;"
			@click="goAuth">
			去认证
			<!-- 认证标记qx -->
		</view>
	</view>
	<view class="form">
		<u--form :model="gysForm" :rules="gysRules" ref="form1" labelPosition="top" labelWidth="150">
			<u-form-item class="formItem" label="标题" prop="title">
				<u--input v-model="gysForm.title" border="none" placeholder="请输入"></u--input>
			</u-form-item>
			<u-form-item class="formItem" label="背景长图" prop="">
				<view class="formItemArea">
					<u-upload :fileList="fileList.fileList0" @afterRead="afterRead($event,0)"
						@delete="deletePic($event,0)" name="1" multiple :maxCount="1"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="缩略图" prop="">
				<view class="formItemArea">
					<u-upload :fileList="fileList.fileList5" @afterRead="afterRead($event,5)"
						@delete="deletePic($event,5)" name="1" multiple :maxCount="1"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="商家优势" prop="merchantAdvantages">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.merchantAdvantages" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList1" @afterRead="afterRead($event,1)"
						@delete="deletePic($event,1)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="服务类型" prop="serviceType">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.serviceType" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList2" @afterRead="afterRead($event,2)"
						@delete="deletePic($event,2)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="律所介绍" prop="lawFirmProfile">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.lawFirmProfile" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList3" @afterRead="afterRead($event,3)"
						@delete="deletePic($event,3)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="服务项目" prop="serviceProgram">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.serviceProgram" maxlength="500" count placeholder="请输入内容"
						border="none">
					</u--textarea>
					<u-upload :fileList="fileList.fileList4" @afterRead="afterRead($event,4)"
						@delete="deletePic($event,4)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="公司地址" prop="address" @click.stop="getMapChoseAddress">
				<u--input class="inputClass" v-model="gysForm.address" disabled disabledColor="#ffffff"
					placeholder="门店地址" border="none"></u--input>
				<u-icon name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item class="formItem" label="联系人" prop="contactUser">
				<u--input v-model="gysForm.contactUser" border="none" placeholder="请输入"></u--input>
			</u-form-item>
			<u-form-item class="formItem" label="手机号" prop="contactPhone">
				<u--input v-model="gysForm.contactPhone" border="none" placeholder="请输入"></u--input>
			</u-form-item>
		</u--form>
		<view class="gysBtn" @click="submitForm()">
			发布
		</view>
	</view>
</template>
<style lang="scss">
	.form {
		width: 686rpx;
		margin: 0 auto;

		.formItem {
			border-bottom: 1rpx solid #e7e7e7;

			.formItemArea {
				width: 100%;
			}
		}
	}

	.gysBtn {
		width: 686rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		background: #CB645E;
		border-radius: 10rpx;
		color: #fff;
		margin: 50rpx auto;
	}
</style>